<?php
/**
 * @package     CiMS.framework
 *
 * @copyright   Copyright (C) 2012 Cimaron Shanahan. All rights reserved.
 * @license     http://opensource.org/licenses/mit-license.php MIT License
 */
defined('CiMS') or die;


require_once 'object.php';

/**
 * CiMS Application Class
 */
class CiMS extends CiMSObject {

	/**
	 * Initialize application
	 */
	public static function initialize($name = 'system', $config_path = NULL) {
		global $cims;
		$cims = self::getInstance($name);
		
		$config = new CiMSObject();
		if ($config_path && file_exists($config_path)) {
			include_once $config_path;
		}
		$cims->set('config', $config);

		$cims->_defines();
		
		//init libraries
		if ($config->getByPath('session/enabled')) {
			$cims->load('session');
		}
		$cims->load('request');
		$cims->load('uri');

		return $cims;
	}

	/**
	 * Override CiMSObject::getInstance()
	 */
	public static function getInstance($name = 'system') {
		return parent::getInstance(array('name' => $name));
	}

	/**
	 * Initialize defines
	 */
	protected function _defines() {
		$path = realpath(dirname(__FILE__));
		define('PATH_SYSTEM', $path);
		define('PATH_HTML', $_SERVER['DOCUMENT_ROOT']);
	}

	/**
	 * Load a library
	 *
	 * @param   string   $name     Library name
	 * @param   array    $config   Config
	 */
	public function load($name, $config = array()) {

		if ($this->has($name)) {
			return $this->get($name);
		}

		$path = PATH_SYSTEM.'/'.$name.'.php';
		$class = 'CiMS'.$name;

		if (file_exists($path)) {
			include_once $path;
		}

		if (class_exists($class)) {
			$this->set($name, $class::getInstance($config));
		} else {
			return false;
		}

		return $this->get($name);
	}

}

